package com.samuel.controller;

import com.samuel.entities.CommonResult;
import com.samuel.entities.Payment;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author a neng huang
 * @since 2021-02-26 20:09
 */
@Log4j2
@RestController
@RequestMapping("consumer/api")
public class PaymentController {
    // public static final String URL = "http://localhost:8001/payment/api/";
    private static final String URL = "http://cloud-payment-service/payment/api/";
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("get/{id}")
    public CommonResult<?> get(@PathVariable("id") String id) {
        return restTemplate.getForObject(URL + "get/" + id, CommonResult.class);
    }

    @GetMapping("list")
    public CommonResult<?> list() {
        return restTemplate.getForObject(URL + "list", CommonResult.class);
    }

    @GetMapping("save")
    public CommonResult<?> save(Payment payment) {
    	log.info("发送保存支付流程");

        return restTemplate.postForObject(URL + "save", payment, CommonResult.class);
    }

    /** 获取Eureka客户端在服务器上的注册信息，是为了给调用端明确调用的接口信息 **/
    @GetMapping("about")
    public Object about() {
        List<String> services = discoveryClient.getServices();
        services.forEach(service-> {
            log.info("service is: {}", service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            instances.forEach(instance-> log.info("instance is: {}", instance));
        });
        return discoveryClient;
    }
}
